package com.itbaizhan.paymentdemo.controller;

import com.alibaba.fastjson.JSON;
import com.itbaizhan.paymentdemo.config.WxPayConfig;
import com.itbaizhan.paymentdemo.service.IWxPaymentService;

import com.itbaizhan.paymentdemo.utils.HttpUtils;
import com.itbaizhan.paymentdemo.utils.WxVerifierUtils;
import com.itbaizhan.paymentdemo.vo.BaseResult;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.HashMap;

//微信支付接口
@Slf4j
@RestController
@RequestMapping("/api/wx-pay")
public class WxPayController {

    @Autowired
    private IWxPaymentService wxPaymentService;
    @Autowired
    private Verifier verifier;
    @Autowired
    private WxPayConfig wxPayConfig;

    @PostMapping("/native/{orderNo}")
    public BaseResult nativePay(String orderNo) throws IOException {

        BaseResult baseResult = wxPaymentService.nativePay(orderNo);
        return baseResult;
    }

    /**
     * 微信支付通知
     * @param request   从微信发来的数据，取出数据
     * @param response   接收微信发来的数据，进行处理
     * @return
     */
    @PostMapping("/native/notity")
    public String notify(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, GeneralSecurityException {
           HashMap<String,String> responseMap = new HashMap<>();
        //1处理通知参数,获取报文参数

        String body = HttpUtils.readData(request);
        //把json 转换为map
        HashMap<String,Object> bodyMap = JSON.parseObject(body,HashMap.class);

        log.info("支付通知id=======> {}",bodyMap.get("id"));
        log.info("支付通知完整数据======》 {}",body);

        //TODO  签名验证 确保是微信给我们发的消息
         boolean verifier = WxVerifierUtils.verifier(request,this.verifier,body);
         if(!verifier){
             response.setStatus(200);
             responseMap.put("code","false");
             responseMap.put("message","失败");
             return JSON.toJSONString(responseMap);
         }

         //TODO： 处理订单    未支付改为已支付
        wxPaymentService.updateOrderStatus(bodyMap);


        //TODO   处理验证   成功应答
        //成功应答：成功就是200，否则就是失败
        response.setStatus(200);
        responseMap.put("code","success");
        responseMap.put("message","成功");
        return JSON.toJSONString(responseMap);
    }


    //   /api/wx-pay/queryOrderStatus/{orderNO}

    /**
     * 查询订单
     * @param ordeNO
     * @return
     * @PathVariable 使用@PathVariable可以快速的访问，URL中的部分内容。
     *
     *  在@RequestMapping的value中使用URI template（{变量名}），
     * 然后在@RequestMapping注解方法的需要绑定的参数前，
     * 使用@PathVariable指定变量名（如果变量名和参数名一致也可以不指定），
     * 从而将URL中的值绑定到参数上。
     */
    @GetMapping("/queryOrderStatus/{orderNo}")
    public BaseResult queryOrderStatus(@PathVariable String ordeNO) throws IOException {

        return BaseResult.ok(wxPaymentService.queryOrder(ordeNO));
    }

    /**
     * 关闭订单
     * @return
     */
    @PostMapping("/cancel/{orderNo}")
    public BaseResult cancel(@PathVariable String orderNO) throws IOException {

        wxPaymentService.cancelOrderNo(orderNO);
        return BaseResult.ok();
    }

    //退款
    @PostMapping("/refund/{orderNo}/{reason}")
    public BaseResult refund(@PathVariable String orderNO,@PathVariable String reason) throws IOException {
        wxPaymentService.refund(orderNO, reason);
        return BaseResult.ok();
    }

    //退款接口，向微信发送了请求接口，返回的数据
    @PostMapping("/refunds/notity")
    public String refunds(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, GeneralSecurityException {
        HashMap<String, String> responseMap = new HashMap<>();
        //1处理通知参数,获取报文参数

        String body = HttpUtils.readData(request);
        //把json 转换为map
        HashMap<String,Object> bodyMap = JSON.parseObject(body,HashMap.class);

        log.info("支付通知id=======> {}",bodyMap.get("id"));
        log.info("支付通知完整数据======》 {}",body);

        //TODO  签名验证 确保是微信给我们发的消息
        boolean verifier = WxVerifierUtils.verifier(request,this.verifier,body);
        if(!verifier){
            response.setStatus(200);
            responseMap.put("code","false");
            responseMap.put("message","失败");
            return JSON.toJSONString(responseMap);
        }

        //处理退款
        wxPaymentService.processRefunds(bodyMap);

        //成功应答：成功就是200，否则就是失败
        response.setStatus(200);
        responseMap.put("code","success");
        responseMap.put("message","成功");
        return JSON.toJSONString(responseMap);
    }
}
